package com.web.exiaodao.remote.service.impl;

import com.alibaba.fastjson.JSON;
import com.web.exiaodao.business.entity.FranchiseTable;
import com.web.exiaodao.business.repository.FranchiseTableRepository;
import com.web.exiaodao.remote.service.ApiFranchiseTableService;
import com.web.exiaodao.remote.vo.FranchiseTableVo;
import com.web.webstart.base.constant.XaConstant;
import com.web.webstart.base.exception.BusinessException;
import com.web.webstart.base.service.impl.BaseService;
import com.web.webstart.base.util.XaUtil;
import com.web.webstart.base.util.jpa.DynamicSpecifications;
import com.web.webstart.base.util.jpa.SearchFilter;
import com.web.webstart.base.util.jpa.SearchFilter.Operator;
import com.web.webstart.base.util.result.XaResult;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigInteger;
import java.util.List;
import java.util.Map;

/**
 * @author: zhangl
 * @times: 2015-5-15下午06:46:35
 * 类的说明：前端APIFranchiseTable接口实现类
 **/
@Service("ApiFranchiseTableService")
@Transactional(readOnly = false)
public class ApiFranchiseTableServiceImpl extends BaseService<FranchiseTable> implements ApiFranchiseTableService {

    private static final Logger LOGGER = Logger.getLogger(ApiFranchiseTableServiceImpl.class);

    @Autowired
    FranchiseTableRepository franchiseTableRepository;

    @Override
    public XaResult<FranchiseTableVo> findOne(Long tId) throws BusinessException {
        FranchiseTable obj = franchiseTableRepository.findByIdAndStatusNot(tId, XaConstant.Status.delete);
        XaResult<FranchiseTableVo> xr = new XaResult<FranchiseTableVo>();
        if (XaUtil.isNotEmpty(obj)) {
            xr.setObject(JSON.parseObject(JSON.toJSONString(obj), FranchiseTableVo.class));
            xr.getObject().setId(obj.getId());
            LOGGER.info("查询单个实体----->FranchiseTable");
        } else {
            xr.error(XaConstant.Message.object_not_find);
            LOGGER.info(XaConstant.Message.object_not_find);
        }
        return xr;
    }

    @Override
    public XaResult<List<FranchiseTableVo>> findListNEStatusByFilter(
            Integer status, Map<String, Object> filterParams, Pageable pageable)
            throws BusinessException {
        Map<String, SearchFilter> filters = SearchFilter.parse(filterParams);
        if (status == null) {// 默认显示非删除的所有数据
            status = XaConstant.Status.delete;
        }
        filters.put("status", new SearchFilter("status", Operator.NE, status));
        Page<FranchiseTable> page = franchiseTableRepository.findAll(DynamicSpecifications
                .bySearchFilter(filters.values(), FranchiseTable.class), pageable);
        XaResult<List<FranchiseTableVo>> xr = new XaResult<List<FranchiseTableVo>>();
        xr.setObject(JSON.parseArray(JSON.toJSONString(page.getContent()), FranchiseTableVo.class));
        for (int i = 0; i < page.getContent().size(); i++) {
            xr.getObject().get(i).setId(page.getContent().get(i).getId());
        }
        return xr;
    }

    @Override
    public XaResult<List<FranchiseTableVo>> findListEQStatusByFilter(
            Integer status, Map<String, Object> filterParams, Pageable pageable)
            throws BusinessException {
        Map<String, SearchFilter> filters = SearchFilter.parse(filterParams);
        if (status == null) {// 默认显示正常数据
            status = XaConstant.Status.valid;
        }
        filters.put("status", new SearchFilter("status", Operator.EQ, status));
        Page<FranchiseTable> page = franchiseTableRepository.findAll(DynamicSpecifications
                .bySearchFilter(filters.values(), FranchiseTable.class), pageable);
        XaResult<List<FranchiseTableVo>> xr = new XaResult<List<FranchiseTableVo>>();
        xr.setObject(JSON.parseArray(JSON.toJSONString(page.getContent()), FranchiseTableVo.class));
        for (int i = 0; i < page.getContent().size(); i++) {
            xr.getObject().get(i).setId(page.getContent().get(i).getId());
        }
        return xr;
    }

    @Override
    public XaResult<FranchiseTableVo> multiOperate(String modelIds,
                                                   Integer status) throws BusinessException {
        XaResult<FranchiseTableVo> xr = new XaResult<FranchiseTableVo>();
        if (status == null) {
            status = XaConstant.Status.delete;
        }
        if (modelIds != null) {
            String[] ids = modelIds.split(",");
            for (String id : ids) {
                FranchiseTable obj = franchiseTableRepository.findByIdAndStatusNot(Long.parseLong(id), status);
                if (XaUtil.isNotEmpty(obj)) {
                    obj.setStatus(status);
                    obj = franchiseTableRepository.save(obj);
                    xr.setObject(JSON.parseObject(JSON.toJSONString(obj), FranchiseTableVo.class));
                    xr.getObject().setId(obj.getId());
                }
            }
        }
        LOGGER.info("更改数据状态----->FranchiseTable");
        return xr;
    }

    @Override
    public XaResult<FranchiseTableVo> createModel(FranchiseTable model)
            throws BusinessException {
        XaResult<FranchiseTableVo> xr = new XaResult<FranchiseTableVo>();
        FranchiseTable obj = franchiseTableRepository.save(model);
        xr.setObject(JSON.parseObject(JSON.toJSONString(obj), FranchiseTableVo.class));
        xr.getObject().setId(obj.getId());
        LOGGER.info("新增数据成功----->FranchiseTable");
        return xr;
    }

    @Override
    public XaResult<FranchiseTableVo> updateModel(FranchiseTable model)
            throws BusinessException {
        FranchiseTable obj = franchiseTableRepository.findOne(model.getId());
        XaResult<FranchiseTableVo> xr = new XaResult<FranchiseTableVo>();
        if (XaUtil.isNotEmpty(obj)) {
            obj.setUserId(XaUtil.isNotEmpty(model.getUserId()) ? model.getUserId() : obj.getUserId());
            obj.setCustomer_Name(XaUtil.isNotEmpty(model.getCustomer_Name()) ? model.getCustomer_Name() : obj.getCustomer_Name());
            obj.setCellphone(XaUtil.isNotEmpty(model.getCellphone()) ? model.getCellphone() : obj.getCellphone());
            obj.setFranchise_Unit_Name(XaUtil.isNotEmpty(model.getFranchise_Unit_Name()) ? model.getFranchise_Unit_Name() : obj.getFranchise_Unit_Name());
            obj.setFranchise_Unit_PicUrls(XaUtil.isNotEmpty(model.getFranchise_Unit_PicUrls()) ? model.getFranchise_Unit_PicUrls() : obj.getFranchise_Unit_PicUrls());
            obj.setFranchise_State(XaUtil.isNotEmpty(model.getFranchise_State()) ? model.getFranchise_State() : obj.getFranchise_State());
            obj.setRefuse_Reason(XaUtil.isNotEmpty(model.getRefuse_Reason()) ? model.getRefuse_Reason() : obj.getRefuse_Reason());
            obj.setAgreements(XaUtil.isNotEmpty(model.getAgreements()) ? model.getAgreements() : obj.getAgreements());
            obj = franchiseTableRepository.save(obj);
            xr.setObject(JSON.parseObject(JSON.toJSONString(obj), FranchiseTableVo.class));
            xr.getObject().setId(obj.getId());
        } else {
            xr.error(XaConstant.Message.object_not_find);
        }
        LOGGER.info("编辑数据成功----->FranchiseTable");
        return xr;
    }

    /**
     * 查询最新一条的数据
     *
     * @return XaResult<FranchiseTableVo>
     */
    @Override
    public XaResult<FranchiseTableVo> findFranchiseInfo(long userId) {
        XaResult<FranchiseTableVo> xr = new XaResult<FranchiseTableVo>();
        String sql = "SELECT id, user_id, franchise_state, refuse_reason, customer_name, cellphone, franchise_unit_name, franchise_unit_pic_urls FROM tb_xa_franchisetable WHERE status <> 3 AND user_id = " + userId + " ORDER BY create_time desc LIMIT 1";
        List<Object[]> objs = this.query(sql, null, null);
        if (XaUtil.isNotEmpty(objs) && objs.size() > 0) {
            FranchiseTableVo vo = new FranchiseTableVo();
            vo.setId(((BigInteger) objs.get(0)[0]).longValue());
            vo.setUserId(((BigInteger) objs.get(0)[1]).longValue());
            vo.setFranchise_State(objs.get(0)[2] == null ? 1 : (int) objs.get(0)[2]);
            vo.setRefuse_Reason((String) objs.get(0)[3]);
            vo.setCustomer_Name((String) objs.get(0)[4]);
            vo.setCellphone((String) objs.get(0)[5]);
            vo.setFranchise_Unit_Name((String) objs.get(0)[6]);
            vo.setFranchise_Unit_PicUrls((String) objs.get(0)[7]);
            xr.success(vo);
        } else {
            xr.error("暂无申请信息");
            xr.setCode(XaConstant.Code.success);
        }
        return xr;
    }
}
